import { Injectable } from '@angular/core';
import { LeanCloudService } from 'app/utils/lean-cloud.service'
import { Observable } from 'rxjs'
import { NetService } from 'app/utils/net.service'
import { userService } from 'app/config/server'
@Injectable()
export class UserManageService {

  constructor(
    private leanCloudService: LeanCloudService,
    private netService: NetService
  ) { }

  /**
   * 获取用户列表
   */
  getUsers(page) {
    return this.leanCloudService.send(
      ({ leancloud }) => leancloud.Query('user', page)
        .find())
  }

  /**
   * 获取用户信息
   */
  getUser(id) {
    return this.leanCloudService.send(
      ({ leancloud }) => leancloud.Query('user')
        .get(id)
        .then(data => data.toJSON()))
  }

  /**
   * 更新用户信息
   * @param id
   * @param param1
   */
  updateUser(id, { username, realname, email, phonenumber }) {
    // 第一个参数是 className，第二个参数是 objectId
    var todo = this.leanCloudService.Object.createWithoutData('user', id);
    // 修改属性
    todo.set('username', username);
    todo.set('realname', realname);
    todo.set('email', email);
    todo.set('phonenumber', phonenumber);
    // 保存到云端
    return todo.save();
  }

  /**
   * 添加用户
   */
  addUser({ username, realname, email, phonenumber }) {
    return this.netService.send({
      service: userService.addUser,
      params: {
        username,
        realname,
        email,
        phonenumber
      }
    })
  }

  deleteUser(id) {
    var todo = this.leanCloudService.Object.createWithoutData('user', id);
    todo.destroy().then(function (success) {
      // 删除成功
    }, function (error) {
      // 删除失败
    });
  }
}
